package com.sky.task;

import com.sky.entity.Orders;
import com.sky.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类，处理订单状态
 */

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrdersService ordersService;

    /**
     * 处理超时未支付订单
     */
    @Scheduled(cron = "0 * * * * ?") // 每分钟触发一次
//    @Scheduled(cron = "1/5 * * * * ?")
    public void processTimeOutOrder() {
        log.info("处理超时订单:{}", LocalDateTime.now());

        // 查询订单数据
        // 状态符合，时间符合
        Integer status = Orders.PENDING_PAYMENT;
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);

        // 查询指定条件订单
        List<Orders> ordersList = ordersService.queryByStatusAndTime(status, time);

        if (ordersList != null && !ordersList.isEmpty()) {
            for (Orders order : ordersList) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时未支付，取消");
                order.setCancelTime(LocalDateTime.now());
                ordersService.updateById(order);
            }
        }

    }

    /**
     * 处理派送中订单
     */
    @Scheduled(cron = "0 0 1 * * ?") // 每日触发一次
//    @Scheduled(cron = "0/5 * * * * ?")
    public void processDeliveryOrder() {
        log.info("处理派送中订单:{}", LocalDateTime.now());

        // 查询订单数据
        // 状态符合，时间符合
        Integer status = Orders.DELIVERY_IN_PROGRESS;
        LocalDateTime time = LocalDateTime.now().minusHours(1);

        // 查询指定条件订单
        List<Orders> ordersList = ordersService.queryByStatusAndTime(status, time);

        if (ordersList != null && !ordersList.isEmpty()) {
            for (Orders order : ordersList) {
                order.setStatus(Orders.COMPLETED);
                order.setCancelReason("订单超时未支付，取消");
                order.setCancelTime(LocalDateTime.now());
                ordersService.updateById(order);
            }
        }

    }
}
